package top.i51213.fastaction.uri;

import java.nio.charset.StandardCharsets;

public class ReaderUtil {
    private static boolean match(byte[] h, int[] offsets, byte[] codes) {
        boolean b = true;
        for (int i = 0, index; i < offsets.length; i++) {
            index = offsets[i];
            b = b && (h[index] == codes[i]);
        }
        return b;
    }

    private static boolean match(byte[] h, byte[] codes) {
        boolean b = true;
        for (int i = 0; i < codes.length; i++) {
            b = b && (h[i] == codes[i]);
        }
        return b;
    }

    public static MimeType findMimeType(byte[] h) {
        if (match(h, new byte[]{(byte) 0xff, (byte) 0xd8, (byte) 0xff, (byte) 0xe0}) //
                || match(h, new byte[]{(byte) 0xff, (byte) 0xd8, (byte) 0xff, (byte) 0xe1})//
                || match(h, new byte[]{(byte) 0xff, (byte) 0xd8, (byte) 0xff, (byte) 0xe8})) {
            return MimeType.Image.Jpeg;
        } else if (match(h, new byte[]{(byte) 0x89, (byte) 0x50, (byte) 0x4e, (byte) 0x47})) {
            return MimeType.Image.Png;
        }else if (match(h,new int[]{0,1,2,3,8,9,10,11,12,13,14}, new byte[]{'R','I','F','F','W','E','B','P','V','P','8'})) {
            return MimeType.Image.Webp;
        }else if (match(h,"%PDF-".getBytes(StandardCharsets.UTF_8))) {
            return MimeType.Application.Pdf;
        }else if (match(h,new byte[]{(byte) 0x50, (byte) 0x4b})) {
            return MimeType.Application.Zip;
        }
        return MimeType.Others.Any;
    }
}
